package com.i2863.shiroDemo.config;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.web.servlet.ShiroHttpServletRequest;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.apache.shiro.web.session.mgt.WebSessionManager;
import org.apache.shiro.web.util.WebUtils;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.Serializable;

/**
 * OssWebSessionManager
 *
 * @author cexy
 * @description:
 * @date 2020/8/7
 * @time 10:48
 */
/**
 * @author cexy
 * @date 2021/5/17 10:43
 * @description  重写shiro的session获取，使能token登录
 **/
@Slf4j
public class OssWebSessionManager extends DefaultWebSessionManager implements WebSessionManager {

    /**
     * 这个是客户端请求给服务端带的header
     */
    private static final String REFERENCED_SESSION_ID_SOURCE = "Stateless request";

    /**
     * 重写getSessionId,分析请求头中的指定参数，做用户凭证sessionId
     */
    @Override
    protected Serializable getSessionId(ServletRequest request, ServletResponse response) {
        String sessionId = WebUtils.toHttp(request).getHeader(Constant.HEADER_TOKEN_NAME);
        //System.out.println("id："+id);
        if (StringUtils.isEmpty(sessionId)) {
            //如果没有携带id参数则按照父类的方式在cookie进行获取
            //System.out.println("super："+super.getSessionId(request, response));
            return super.getSessionId(request, response);
        } else {
            //如果请求头中有 authToken 则其值为sessionId
            request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_SOURCE, REFERENCED_SESSION_ID_SOURCE);
            request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID, sessionId);
            request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_IS_VALID, Boolean.TRUE);
            return sessionId;
        }
    }
}